
<template>
  <div @paste="handlePaste" ref="uploadContainerRef">
    <el-upload
        ref="uploadRef"
        :action="actionApi" v-model:file-list="fileList"  :class="'custom-upload '+cls"
        :show-file-list="true" list-type="picture-card" :on-remove="handleRemove1" :on-change="handleChange"
        name="file" multiple
        :auto-upload="auto"
        :headers="{ authorization: token, 'Request-from': 'Dashboard' }"
        v-bind="$attrs" :on-progress="handleProgress" :before-upload="beforeUpload"
        :on-success="handleSuccess"
    >
        <template v-for="(index, name) in $slots" v-slot:[name]>
            <slot :name="name"></slot>
        </template>
        <template #file="{ file }">
            <div >
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" :class="imageClass">
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <el-icon><ZoomIn/></el-icon>
                  </span>
<!--                  <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">-->
<!--                    <el-icon><Download/></el-icon>-->
<!--                  </span>-->
                  <span v-if="!disabled && isadd" class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon><Delete/></el-icon>
                  </span>
                  <span @click="handleTop(file)" title="置顶" v-if="isadd">
                    <el-icon><ArrowUpBold /></el-icon>
                  </span>
                  <span @click="handleLeft(file)" style="margin-left: 0" title="前移" v-if="isadd">
                    <el-icon><ArrowLeft /></el-icon>
                  </span>
                   <span  @click="handleRight(file)" style="margin-left: 0" title="后移" v-if="isadd">
                    <el-icon><ArrowRight /></el-icon>
                  </span>
              </span>
            </div>
        </template>
        <div class="w-24 h-24 border-blue-100 border-dashed border rounded flex justify-center pt-8" >
          <el-icon><Plus/></el-icon>
        </div>
    </el-upload>

    <!--    <el-upload :action="uploadUrl" list-type="picture-card" :auto-upload="true" :on-remove="handleRemove1"  :on-change="handleChange" >-->
    <!--        <el-icon><Plus/></el-icon>-->
    <!--        <i slot="default" class="el-icon-plus"></i>-->
    <!--    </el-upload>-->

    <el-dialog v-model="dialogVisible" append-to-body>
        <img w-full :src="dialogImageUrl" alt="Preview Image"/>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref,onMounted, onBeforeUnmount} from 'vue'
import Message from '@/utils/message2'
import { Delete, Download, Plus, ZoomIn,ArrowLeft,ArrowRight,ArrowUpBold } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile, UploadFile } from 'element-plus'
import BMF from "browser-md5-file"; //这个使用npm

const props = defineProps({
    action: {
        type: String,
        default: '/upload-file',
    },
    auto: {
        type: Boolean,
        default: true,
    },
    isadd: {
        type: Boolean,
        default: true,
    },
    modelValue: {
        type: Array,
        default: [],
        require: true,
    },
    imageClass: {
        type: String,
        default: 'upload-img',
    },
    cls: {
        type: String,
        default: 'upload-img',
    },
})

const emits = defineEmits(['update:modelValue','isUploading'])


const fileList = ref<UploadUserFile[]>()
setTimeout(function (){
    fileList.value = props.modelValue as UploadUserFile[]
},1500)

const dialogImageUrl = ref<string|undefined>('')
const dialogVisible = ref(false)
const disabled = ref(false)


const handleRemove1 = (file:any, fileList:any) => {
    console.log(222444, file, fileList);
}
const handleRemove = (file:any) => {
    const index = fileList.value.indexOf(file)
    if (index !== -1) {
        fileList.value.splice(index, 1)
    }
    emits('update:modelValue', fileList.value)
}
const handleChange = (file:any, fileList:any) => {
    console.log(222, fileList, file);
}
const handleProgress = (event, file, fileList) =>{
    emits('isUploading', true)
}
const handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true;
}
const handleLeft = (file:any) => {
    const idx = fileList.value.indexOf(file)
    if (idx !== -1 && idx !=0 && idx !=undefined && fileList.value?.length>1) {
        fileList.value[idx] = fileList.value[idx-1]
        fileList.value[idx-1] = file
    }
}
const handleRight = (file:any) => {
    const idx = fileList.value.indexOf(file)
    if (idx !== -1 && idx+1 !=fileList.value?.length  && idx !=undefined && fileList.value?.length>1) {
        fileList.value[idx] = fileList.value[idx+1]
        fileList.value[idx+1] = file
    }
}
const handleTop = (file:any) => {
    const idx = fileList.value.indexOf(file)
    if (idx !== -1 && idx !=0 ) {
        fileList.value.splice(idx, 1)
        fileList.value?.unshift(file)
    }
}

//获取文件的MD5值 await getMd5(rawFile);
const getMd5 = (rawFile) => {
    return new Promise((resolve, reject) => {
        const bmf = new BMF();
        bmf.md5(rawFile,(err: any, md5: any) => {
                resolve(md5);
            },(progress: any) => {}
        );
    });
};

//上传前检查图片
const beforeUpload = async (rawFile) => {
    let md5 = await getMd5(rawFile)
    let checkHas = fileList.value?.filter((x:any)=>x.md5 == md5||x?.response?.data?.md5 == md5).length
    if(checkHas !=undefined && checkHas>0){
        Message.warning('图片已存在')
        return false
    }else{
        if (rawFile.size / 1024 / 1024 > 6) {
            Message.error('图片不能超过6MB!')
            return false
        }
    }
    return true
}
const actionApi = ref<string>('')
const fileIds = ref([])
import {message} from "@/utils/message";
import {formatToken, getToken} from "@/utils/auth";
const { VITE_APP_BASE_API } = import.meta.env;
// actionApi.value = VITE_APP_BASE_API + props.action
actionApi.value = VITE_APP_BASE_API + (VITE_APP_BASE_API.endsWith('/')?'upload-file':'/upload-file')

const token = ref<string>()
token.value = formatToken(getToken().accessToken)

const handleSuccess = (response: any) => {
    if (response.code === 10000) {
        emits('update:modelValue', [...props.modelValue, response.data])
        emits('isUploading', false)
    } else {
        Message.error(response.message)
    }
}

const uploadRef = ref()
const uploadContainerRef = ref()
const handlePaste = async (event) => {
  if(objStr.value =='custom-upload '+props.cls){
    // 1. 获取剪贴板数据
    const clipboardData = event.clipboardData || window.clipboardData;
    if (!clipboardData) return;

    // 2. 遍历剪贴板中的文件项，查找图片
    const items = clipboardData.items;
    for (const item of items) {
      if (item.type.indexOf('image') !== -1) {
        // 3. 提取图片文件
        const file = item.getAsFile();
        if (!file) return;
        // 4. 将文件添加到 el-upload 的文件列表
        if (uploadRef.value) {
          // 如果是自动上传（auto-upload=true），直接添加到队列
          uploadRef.value.handleStart(file);
          uploadRef.value.submit()
          event.preventDefault(); // 阻止其他组件处理相同事件
          // 如果需要手动上传（auto-upload=false），调用 uploadRef.value.submit()
        }
      }
    }
  }
};
const objStr = ref('')
onMounted(() => {
  document.addEventListener('paste', handlePaste);
  document.addEventListener('mouseover', (event) => {
    const divUl = event.target.closest('ul.el-upload-list');
    if (divUl) {
      objStr.value = divUl.parentElement.className;
    }
  });
});

onBeforeUnmount(() => {
  document.removeEventListener('paste', handlePaste);
});
</script>
<style scoped>
/* 调整图片的宽度和高度 */
:deep(.el-upload-list--picture .el-upload-list__item) {
  width: 120px;
  height: 120px;
}
:deep(.el-upload-list--picture-card .el-upload--picture-card) {
  --el-upload-picture-card-size: 120px;
}

/* 调整卡片模式的尺寸 */
:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
}
:deep(div.el-upload.is-disabled){
  /*display:none*/
}
</style>
